# -*- coding:utf-8 -*-
__author__ = 'weikai'
from twisted.internet import defer, reactor
from stompest.config import StompConfig
from stompest.protocol import StompSpec
from stompest.sync.client import Stomp
import traceback
import  threading
import json
from utils import send_complete_flag
import settings as se
from datetime import datetime
from request_cic.login import *
from session import getSession
from request_cic.EntranceRenwal import cic_entrance_renwal
from request_epicc.log import Logger
from realtimeThread import plateNo_getSource
from request_pingan.entrance import is_pingan_renwal
from request_pingan.utils import compare_time40
from gevent import monkey
from common.MqSend import send_mq
from my_dbUtil.sql.my_sql import inser_user_renewal,query_user_renewal,query_user_permium_time
from common import config
import gevent
import time
monkey.patch_socket()
monkey.patch_ssl()
monkey.patch_all()
log=Logger()
'''
监听车牌号队列
'''
ERROR_QUEUE = '/queue/testConsumerError'
CONFIG = StompConfig(se.MQHOST)
QUEUE = se.COMPLETE_PLATE_NUMBER
EPICC=se.EPICC_PLATE_NUMBER
CJBX=se.CJBX_PLATE_NUMBER
log=Logger()

def runrealtime():
    try:
        client = Stomp(CONFIG)
        client.connect()
        #client.subscribe(QUEUE, {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
        client.subscribe(QUEUE, {StompSpec.ACK_HEADER: StompSpec.ACK_AUTO})
        while True:
            try:
                frame = client.receiveFrame()
                body=json.loads(frame.body.decode())[0]
                insuranceType=body.get("insuranceType",[])[0]
                body['insuranceType']=insuranceType
                client.send(body=json.dumps(body,ensure_ascii=False).encode(),destination=EPICC)
                client.send(body=json.dumps(body,ensure_ascii=False).encode(),destination=CJBX)
                #body=json.loads(frame.body.decode())
                log.info('Got %s' % json.dumps(body,ensure_ascii=False))
                #client.ack(frame)
                is_renwal_all(body,client=client)
            except Exception,e:
                log.error(e)
                log.error(frame.body)
                log.error(traceback.format_exc())

    except Exception as e:
            log.error(e)
            log.error(traceback.format_exc())

def is_renwal_all(data,client=None):
    sessiondt=""
    sessiondt = getSession()
    requestcic = sessiondt['4']
    loginRes=sessiondt['5']
    pingansession=sessiondt['1']


    plateNumber=data['plateNumber']
    if len(plateNumber)!=7:
        log.error(u'plateNumber len != 7')
        return
    insureCarId=data['insureCarId']
    sessionId=data['sessionId']
    isPhone=data['isPhone']
    insuranceType=data['insuranceType']
    #insureTypeGroupId=data.get("insureTypeGroupId","9999")

    carInfo=0
    sql_carInfo=query_user_renewal(plateNumber)
    if sql_carInfo==0:
        g1=gevent.spawn(cic_entrance_renwal,requestcic,plateNumber)
        g2=gevent.spawn(is_pingan_renwal,pingansession,plateNumber)
        gevent.joinall([g1,g2])
        cic_out=g1.value
        pingan_out=g2.value
        #cic_out=pingan_out=0

        if cic_out!=0 or pingan_out!=0 :
            if isinstance(cic_out,dict):
                carInfo=cic_out
                inser_user_renewal(carInfo)
            else :
                carInfo=pingan_out
                inser_user_renewal(carInfo)

        if cic_out==0 and pingan_out==0:
            carInfo=query_user_renewal(plateNumber)
            if carInfo==0:
                time.sleep(5)
                carInfo=query_user_renewal(plateNumber)
        #通过行业协会进行查询
        if carInfo==0:
            carInfo=query_user_permium_time(plateNumber)
            if carInfo!=0:
                carInfo['insuredAddress']=""
                carInfo['mobile']=""
        if carInfo==0:
            #不是续保用户
            #添加队列
            send_complete_flag(client,plateNumber,"0",isPhone,sessionId)
            log.info("plateNumber %s = 0" % plateNumber)
    else:
        carInfo=sql_carInfo

    #如果是续保用户
    if carInfo!=0:
        send_complete_flag(client,plateNumber,"1",isPhone,sessionId,carInfo)
        #40天之外的用户 直接返回
        carInfo['insuranceType']=insuranceType
        insureTypeGroupId=insuranceType.get("insuranceTypeGroupId","")
        insuranceTypeGroup=insuranceType.get("insuranceTypeGroup","")
        endDate=carInfo.get("endDate","")

        if endDate!="":
            min_time=compare_time40(endDate)
            if min_time > config.days:
                log.error(u"查询在40天内的 最近一期的保险结束时间为 %s" % endDate)
                send_mq(client,plateNumber,"查询在40天内的 最近一期的保险结束时间为 %s" % endDate ,"2","2",sessionId,isPhone,insureTypeGroupId,insuranceTypeGroup)
                return

        carInfo['4']=requestcic
        carInfo['5']=loginRes
        carInfo['1']=sessiondt['1']
        #添加client
        carInfo['insureCarId']=insureCarId
        carInfo['client']=client
        carInfo['sessionId']=sessionId
        carInfo['isPhone']=isPhone
        plateNo_getSource(carInfo)
        #爬取

def add():
    return 1
#方法运行
threads = []
log.info(u"程序开始运行%s" % datetime.now())

for arg in xrange(10):
    th = threading.Thread(target=runrealtime)
    th.start()
    threads.append(th)
try:
    for th in threads:
        th.join()
except Exception,e:
    log.error(e)
    log.error(traceback.format_exc())
log.info(u"程序结束运行%s" % datetime.now())

